<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input class="filter-item" placeholder="请输入代理商名称" v-model="params.agentLinkName" style="width: 200px;" clearable></el-input>
      <el-input class="filter-item" placeholder="联系人手机号" v-model="params.agentLinkTel" style="width: 150px;" clearable></el-input>
      <el-input class="filter-item" placeholder="联系人" v-model="params.agentName" style="width: 150px;" clearable></el-input>
      <el-button class="filter-item" type="primary" icon="el-icon-edit-outline" @click="getTableData(1)">搜索</el-button>
      <el-button v-if="btnPower.AgentListAdd" class="filter-item" type="primary" icon="el-icon-document" @click="getButton()">添加</el-button>
      <el-button v-if="btnPower.AgentListBaseAuth" class="filter-item" type="primary" icon="el-icon-document" @click="getAgentBaseAuth">基础权限</el-button>
    </div>
    <el-table
      :data="tableData"
      v-loading="listLoading"
      element-loading-text="请稍后"
      border
      fit
      highlight-current-row>
      <el-table-column
              type="index"
              label="序号"
              width="50"
              align="center">
      </el-table-column>
      <el-table-column
              prop="agentName"
              label="联系人名称"
              align="center">
      </el-table-column>
      <el-table-column
              prop="agentLinkName"
              label="代理商名称"
              align="center">
      </el-table-column>
      <el-table-column
              prop="agentLinkTel"
              label="联系电话"
              align="center">
      </el-table-column>
      <el-table-column
              prop="agentRate"
              :formatter="getAgentRate"
              label="协议费率(%)"
              align="center">
      </el-table-column>
      <el-table-column
              prop="agentStatus"
              :formatter="status"
              label="状态"
              align="center">
      </el-table-column>
      <el-table-column
              prop="saleName"
              label="所属销售"
              align="center">
      </el-table-column>
      <el-table-column
              prop="agentLinkMail"
              label="邮箱"
              align="center">
      </el-table-column>
      <el-table-column
              prop="createTime"
              :formatter="timeFormat"
              label="创建时间"
              align="center">
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="210">
        <template slot-scope="scope">
          <el-button v-if="btnPower.AgentListBj" type="primary" size="small" @click="getButton(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.userId==null&&btnPower.AgentListBind" type="primary" size="small" @click="getAgentBind(scope.row)">绑定</el-button>
          <el-button v-if="scope.row.userId!=null&&btnPower.AgentListRev" type="primary" size="small" @click="getAgentRev(scope.row)">修改</el-button>
          <el-button v-if="scope.row.userId!=null&&btnPower.AgentListReset" type="primary" size="small" @click="getResetPwd(scope.row)">重置</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="params.current" :limit.sync="params.size" @pagination="getTableData" />


    <el-dialog
      :title="popupType==1?'添加代理商':'编辑代理商'"
      :visible.sync="popup"
      :close-on-click-modal=false
      :destroy-on-close=true
      width="500px"
      center>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="联系人名称" prop="agentName">
            <el-input v-model="ruleForm.agentName"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="agentLinkTel">
            <el-input v-model="ruleForm.agentLinkTel"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="agentLinkMail">
            <el-input v-model="ruleForm.agentLinkMail"></el-input>
        </el-form-item>
        <el-form-item label="代理商名称" prop="agentLinkName">
            <el-input v-model="ruleForm.agentLinkName"></el-input>
        </el-form-item>
        <el-form-item label="协议费率" prop="agentRate">
            <el-input v-model="ruleForm.agentRate">
                <template slot="append">%</template>
            </el-input>
        </el-form-item>

        <el-form-item label="状态" prop="agentStatus">
            <el-radio-group v-model="ruleForm.agentStatus">
                <el-radio label="1">启用</el-radio>
                <el-radio label="0">停用</el-radio>
            </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="popup = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      class="abow_dialog"
      title="分配二级代理商基础权限"
      :visible.sync="agentAuthPopup"
      destroy-on-close=true
      :close-on-click-modal=false
      :destroy-on-close=true
      width="420px"
      center>
      <el-tree
        :data="agentAuthAll"
        style="height: 50vh; overflow: hidden; overflow-y: scroll;"
        show-checkbox
        default-expand-all
        node-key="id"
        ref="tree"
        :props="agentAuthProps">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="agentAuthPopup = false">取 消</el-button>
        <el-button type="primary" @click="getAgentBaseAuthForm">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="agentPopupType==1?'绑定代理商':'修改代理商'"
      :visible.sync="agentPopup"
      :close-on-click-modal=false
      :destroy-on-close=true
      width="500px"
      center>
      <el-form :model="agentForm" :rules="agentRules" ref="agentForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="agentForm.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="账号名" prop="accountNo">
          <el-input v-model="agentForm.accountNo" placeholder="请输入账号名"></el-input>
        </el-form-item>
        <el-form-item label="通道" prop="channelId" ref="channelId">
          <el-select v-model="agentForm.channelId" multiple placeholder="请选择通道" style="width: 100%;">
            <el-option v-for="item in paychannelList" :key="item.id" :label="item.channelName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限">
          <el-tree
            :data="agentAuthAll"
            style="height: 50vh; overflow: hidden; overflow-y: scroll;"
            show-checkbox
            default-expand-all
            node-key="id"
            ref="trees"
            :props="agentProps">
          </el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="agentPopup = false">取 消</el-button>
        <el-button type="primary" @click="agentSubmitForm('agentForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { agentList,addAgent,paychannelList,agentAuthList,agentAuthDist,addAgentBaseAuth,firstAgent, restUser } from '@/api/api.verify.js'

export default {
  components:{Pagination},
  name: 'AgentList',
  data() {
    return {
      btnPower:JSON.parse(localStorage.getItem('btnList')),//按钮权限
      listLoading: true,
      total:0,//总条数
      tableData:[],//列表
      paychannelList:[],//全部支付通道列表
      params:{
        current: 1,
        size: 10,
        agentLinkName:null,//
        agentLinkTel:null,
        agentName:null,
      },//查询条件
      popupType:1,//1 添加  2 编辑
      popup:false,//商超弹窗状态
      ruleForm: {
        id:null,
        agentName: null,//联系人名称
        agentLinkName:null,//代理商名称
        agentStatus: '1',
        channelId:'301',//支付通道ID
        agentLinkTel:null,//联系电话
        agentLinkMail:null,//登录邮箱
        saleName: '',//销售名称
        agentRate:null,//协议费率
        agentNo:null,//代理商编号
      },
      rules: {
        agentName: [
            {required: true, message: '请输入联系人名称', trigger: 'blur'},
        ],
        agentLinkName: [
            {required: true, message: '请输入代理商名称', trigger: 'blur'},
        ],
        channelId: [
            {required: true, message: '请选择支付通道', trigger: 'blur'},
        ],
        agentLinkTel: [
            {required: true, message: '请输入手机号', trigger: 'blur'},
            { max: 11, message: '请输入正确手机号', trigger: 'blur' },
            { pattern: /1[0-9][0-9]{9}/, message: '请输入正确手机号' }
        ],
        agentRate: [
            {required: true, message: '请输入协议费率', trigger: 'blur'},
        ],
        agentStatus: [
            {required: true, message: '', trigger: 'change'}
        ],
        saleName: [
            {required: true, message: '请选择销售人员', trigger: 'change'}
        ],
      },

      agentAuthPopup:false,//一级代理商基础权限弹窗
      agentAuthAll:[],//一级代理商所有菜单按钮列表
      agentAuthDistList:[],//一级代理商基础权限信息
      agentAuthProps: {
        children: 'children',
        label: 'title',
        value: 'id',
      },//一级代理商基础权限树关系

      agentPopup:false,//一级代理商专属权限弹窗
      agentPopupType:1,// 1绑定  2修改
      agentForm:{
        name:null,
        accountNo:null,
        channelId:null,
        channelIds:null,
      },//一级代理商专属权限表单
      agentRules:{
        name: [
            {required: true, message: '请输入名称', trigger: 'blur'},
        ],
        accountNo: [
            {required: true, message: '请输入账号', trigger: 'blur'},
            { max: 11, message: '请输入正确账号(手机号)', trigger: 'blur' },
            { pattern: /1[0-9][0-9]{9}/, message: '请输入正确账号(手机号)' }
        ],
        channelId: [
            {required: true, message: '请选择通道', trigger: 'blur'},
        ],
      },
      agentProps: {
        children: 'children',
        label: 'title',
        value: 'id',
        disabled: this.disabledFn,
      },//一级代理商专属权限树关系
    }
  },
  created() {
    this.getStart()
  },
  methods: {
    getStart(){//初始化
        this.getTableData()
        this.ruleFormCopy = JSON.parse(JSON.stringify(this.ruleForm))
        this.getAgentAuthList()
        this.getPaychannelList();
    },
    getTableData(e) {//获取商超列表
      if(e==1){this.params.current=1;};
      let _this = this
      let data=this.params
      this.listLoading = true
      agentList(data).then(d=>{
        _this.tableData = d.data.records;
        _this.total = Number(d.data.total);
      }).finally(d=>{
        _this.listLoading = false
      });
    },
    getAgentAuthList(){//获取一级代理商菜单按钮列表
      let _this=this
      agentAuthList({}).then(d=>{
        _this.agentAuthAll=d.data
        _this.getAgentAuthDist()
      })
    },
    getPaychannelList(){
      let _this = this;
      paychannelList({}).then(d=>{
           _this.paychannelList = d.data;
       });
    },
    getButton(e){//点击添加编辑商超
      // if(this.paychannelList.length == 0){
      //   this.getPaychannelList();
      // }
      if (e) {//修改
        this.popupType=2
        this.common.coyObj(this.ruleForm,e);
        this.ruleForm.agentRate=(Number(this.ruleForm.agentRate)*100).toFixed(2);
      }else{//添加
        this.popupType=1
        this.ruleForm = JSON.parse(JSON.stringify(this.ruleFormCopy));
      }
      this.popup=true
    },
    submitForm(formName) {//表单验证
      let _this = this;
      this.$refs[formName].validate((valid) => {
        if(valid) {
          _this.getForm()
        } else {
          return false;
        }
      });
    },
    getForm(){//提交表单
      let _this=this
      let method = "POST"
      let alerts = "添加"
      let data = JSON.parse(JSON.stringify(this.ruleForm));
      data.agentRate=(Number(data.agentRate)/100).toFixed(4);
      if(this.popupType==2){
        method = "PUT"
        alerts = "修改"
      }
      addAgent(data,method).then(d=>{
        _this.$message({
          type: 'success',
          message: alerts+'成功!'
        });
        _this.popup=false
        _this.getTableData(1)
      });
    },
    getAgentBaseAuth(){//点击基础权限
      this.agentAuthPopup=true
      this.$nextTick(function() {
        this.$refs.tree.setCheckedKeys(this.agentAuthDistList)
      })
    },
    getAgentAuthDist(){//获取一级代理商基础权限信息
      let _this=this
      agentAuthDist({}).then(d=>{
        let authes=[]
        for (let i=0; i<d.data.length; i++){
          authes.push(d.data[i].authId);
        }
        _this.agentAuthDistList=authes
      })
    },
    getAgentBaseAuthForm(){//添加基础权限表单
      let _this=this
      let authes=this.$refs.tree.getCheckedKeys()
      authes.push.apply(authes, this.$refs.tree.getHalfCheckedKeys())
      let data={}
      data.authes=authes
      addAgentBaseAuth(data).then(d=>{
        _this.$message({
          type: 'success',
          message: '添加成功!'
        });
        _this.agentAuthPopup=false
        _this.getAgentAuthDist()
      })
    },
    getAgentBind(e){//点击代理商绑定 
      this.agentPopup=true
      this.agentPopupType=1
      this.agentForm.name=e.agentName
      this.agentForm.accountNo=e.agentLinkTel
      this.agentForm.extCode=e.agentNo
      this.agentForm.agentId=e.id
      this.agentForm.channelId=null
      this.agentForm.channelIds=null
      this.$nextTick(function() {
        this.$refs.trees.setCheckedKeys(this.agentAuthDistList)
      })
    },
    getAgentRev(e){//点击代理商修改 
      let _this=this
      this.agentPopup=true
      this.agentPopupType=2
      let data={}
      data.userId=e.userId
      firstAgent(data,"GET").then(d=>{
        _this.agentForm.name=d.data.user.name
        _this.agentForm.accountNo=d.data.user.accountNo
        _this.agentForm.id=d.data.user.id
        if(d.data.user.channelIds){
          _this.agentForm.channelId=d.data.user.channelIds.split(",")
          _this.agentForm.channelIds=d.data.user.channelIds
        }
        let authes=[]
        for (let i=0; i<d.data.distAuthes.length; i++){
          authes.push(d.data.distAuthes.[i].authId);
        }
        authes.push.apply(authes, this.agentAuthDistList)
        _this.$refs.trees.setCheckedKeys(authes)
      })
    },
    getResetPwd(e){//重置代理商密码
      let _this=this
      this.$confirm('是否重置（'+e.agentName+'）代理商密码','提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        let data={}
        data.id=e.userId
        restUser(data).then(d=>{
          _this.$message({
              type: 'success',
              message: '重置成功!'
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消重置'
        });
      });
    },
    agentSubmitForm(formName){//表单验证
      let _this = this;
      this.$refs[formName].validate((valid) => {
        if(valid) {
          _this.getAgentForm()
        } else {
          return false;
        }
      });
    },
    getAgentForm(){//点击绑定修改代理商独有权限 确定按钮
      let _this=this
      let data=this.agentForm
      let method="POST"
      let alerts="绑定"
      if(this.agentPopupType==2){
        method="PUT"
        alerts="修改"
      }
      let authes=this.$refs.trees.getCheckedKeys()
      authes.push.apply(authes, this.$refs.trees.getHalfCheckedKeys())
      data.authes=authes
      firstAgent(data,method).then(d=>{
        _this.$message({
          type: 'success',
          message: alerts+'成功!'
        });
        _this.agentPopup=false
        _this.getTableData()
      })
    },

    marketState(row, column, cellValue, index) {//商超状态转换
      let type = row.status;
      if (type == 10) {
        return '开通';
      } else if (type == 20) {
        return '关闭';
      } else {
        return '删除';
      }
    },
    timeFormat(row, column, cellValue, index) {
      return this.common.getLocalTime(parseInt(cellValue));
    },
    getAgentRate(row, column, cellValue, index){
        return (cellValue*100).toFixed(2)
    },
    status(row, column, cellValue, index) {//商超状态转换
        if (cellValue == 1) {
            return '正常';
        } else if (cellValue == 0) {
            return '停用';
        }
    },
    disabledFn(data, node){//代理商独立权限  禁选基础权限
      let authes=this.agentAuthDistList
      for(let i=0;i<authes.length;i++){
        if(data.id==authes[i]){
          return true;
        }
      }
    }
  },
  watch:{
    'params.agentLinkName':function(val){
      let _this=this;
      if(val==""){
        _this.params.agentLinkName=null
      }
    },
    'params.agentLinkTel':function(val){
      let _this=this;
      if(val==""){
        _this.params.agentLinkTel=null
      }
    },
    'params.agentName':function(val){
      let _this=this;
      if(val==""){
        _this.params.agentName=null
      }
    },
    "agentForm.channelId": function (e) {
      this.agentForm.channelIds=e.join(",")
    },
  }
}
</script>

